#!/usr/bin/env python

import os
import logging
import urllib
import datetime

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.ext import db

from idigi import Sample
from config import Config


class ChartHandler(webapp.RequestHandler):
    SOURCE_MAP = {
    }
    VALUE_XFORM_MAP = {
    }
    TITLE_MAP = {
        'xbr0.light': "Light",
		'xbr1.light': "Light2",
		'sensor0.light': "Light3",
        'xbr0.temperature': "Temperature",
		'xbr1.temperature': "Temperature2",
		'sensor0.temperature': "Temperature3",
        'xbib0.led1': "LED1",
		'xbib0.led2': "LED2",
		'xbib0.led3': "LED3",
    }
    def get(self):
        chart = self.request.get('name')

        channel_name = chart
        if channel_name in ChartHandler.SOURCE_MAP:
            channel_name = ChartHandler.SOURCE_MAP[channel_name]

        reference_time = 24
        if Config.DIFFERENCE_FROM_UTC > 0:
          reference_time = 24 - Config.DIFFERENCE_FROM_UTC
        elif Config.DIFFERENCE_FROM_UTC < 0:
          reference_time = 24 + Config.DIFFERENCE_FROM_UTC
        one_day_ago = (datetime.datetime.today() -
               datetime.timedelta(hours=reference_time))
        
        sample_keys = [ ]
        offset = 0
        while 1:
            samples_q = db.Query(Sample, keys_only=True)
            samples_q.filter("channel_name = ", channel_name)
            samples_q.filter("timestamp >= ", one_day_ago)
            ks = samples_q.fetch(1000, offset)
            if len(ks) == 0:
                break
            offset += len(ks)
            sample_keys.extend(ks)
         
        every_n_sample = 1
        if len(sample_keys) > 50:
            every_n_sample = len(sample_keys) / 50
        sample_keys = sample_keys[0::every_n_sample]
        samples_q = db.get(sample_keys)
        
        samples_q = list(samples_q)
        samples_q.sort(lambda p, q: cmp(p.timestamp, q.timestamp))

        xform = lambda x: x
        if chart in ChartHandler.VALUE_XFORM_MAP:
            xform = ChartHandler.VALUE_XFORM_MAP[chart]

        min_x = None
        max_x = None
        min_y = None
        max_y = None
        x_data = [ ]
        y_data = [ ]
        labels = [ ]
        last_label = ""
        sample_counter = 0
        for sample in samples_q:
            x = (sample.timestamp - one_day_ago).seconds
            if sample.unit=="C" or sample.unit=="brightness":
                y = xform(float(sample.value))
            elif sample.unit=="":
                if sample.value=="Off":
                    y = xform(0)
                elif sample.value=="On":
                    y = xform(1)
            if sample_counter == 0:
                min_x = x
                max_x = x
                min_y = y
                max_y = y
            min_x = min(min_x, x)
            max_x = max(max_x, x)
            min_y = min(min_y, y)
            max_y = max(max_y, y)
            x_data.append(str(x))
            y_data.append(str(y))
            last_label = sample.timestamp.strftime("%H:%M:%S")
            if sample_counter % 25 == 0:
                labels.append(last_label)
            else:
                labels.append("")
            sample_counter += 1

        if sample_counter < 25:
            labels[len(labels)-1] = last_label
        
        if not len(x_data):
            min_x = 0
            max_x = 0
            min_y = 0
            max_y = 0
            x_data.append(0)
            y_data.append(0)
            labels.append('undef')
        
        chd = "t:%s|%s" % (','.join(x_data), ','.join(y_data))
        title = chart
        if chart in ChartHandler.TITLE_MAP:
            title = ChartHandler.TITLE_MAP[chart]
        title = urllib.quote_plus(title) + "|Over+24+Hours"
        labels = "|%s|" % '|'.join(labels)
        
        template_values = {
            'chd': chd,
            'title': title,
            'labels': labels,
            'min_x': str(min_x),
            'max_x': str(max_x),
            'min_y': str(min_y),
            'max_y': str(max_y),
        }
        path = os.path.join(os.path.dirname(__file__), 'templates/chart.html')
        self.response.out.write(template.render(path, template_values))


def main():
  logging.getLogger().setLevel(logging.DEBUG)
  application = webapp.WSGIApplication(
                    [
                        ('/chart', ChartHandler),
                    ],
                    debug=True)
  run_wsgi_app(application)


if __name__ == '__main__':
  main()
